package com.wys.mall.search.thread;

import java.util.concurrent.*;

/**
 * 线程测试类
 *
 * @Package com.wys.mall.search.thread
 * @Author charlin
 * @Version: v1.0
 * @Date 2021-07-0310:08
 * @Copyright: 2021 www.wyscha.com Inc. All rights reserved.
 */
public class ThreadTest {

    public static ExecutorService service = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        Runable01 runable01 = new Runable01();
//        new Thread(runable01).start();

//        FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
//        new Thread(futureTask).start();
//        System.out.println(futureTask.get() + "");

        //使用线程池
        Future<?> future = service.submit(new Callable01());
        System.out.println(future.get());

        /**
         * int corePoolSize, 核心线程数，空闲也不消失
         * int maximumPoolSize, 最大线程数
         * long keepAliveTime, (maximumPoolSize-corePoolSize)的存活时间
         * TimeUnit unit, 时间队列
         * BlockingQueue<Runnable> workQueue, 阻塞队列，存活任务，有空闲时到此队列取任务运行
         * ThreadFactory threadFactory, 线程工厂
         * RejectedExecutionHandler handler 队列满了，按照拒绝策略拒绝执行任务
         *
         * 一个线程池 core 7, max 20 , queue 50, 100个线程并发进来如何处理？
         * 首先7个进入core执行，50个进queue，13个进入max执行，多余的30使用拒绝策略丢弃
         */
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                100,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

    }

    public static class Thread01 extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            System.out.println("结果：" + 10 / 2);
        }
    }

    public static class Runable01 implements Runnable {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            System.out.println("结果：" + 10 / 2);
        }
    }

    public static class Callable01 implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            Integer i = 10 / 2;
            System.out.println("结果：" + i);
            return i;
        }
    }
}
